import json
from django import http
from django.db import DataError
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.utils import timezone
from django.views.generic.base import View
from .models import OrderInfo, Payment
from mg.utils.alipay import AliPay
from mg.utils.views import LoginRequiredJSONMixin

# alipay对象
alipay = AliPay(appid='2021000118677733', app_notify_url='http://127.0.0.1:8000/payment/checkPay/',
    app_private_key_path='mg/apps/payment/keys/my_private_key.txt',alipay_public_key_path='mg/apps/payment/keys/alipay_public_key.txt',
    return_url='http://127.0.0.1:8000/payment/checkPay/',debug=True)


class PaymentView(LoginRequiredJSONMixin,View):
    """订单⽀付功能"""

    def post(self,request):
        '''
        获取支付宝支付扫码地址
        :param request:
        :return:
        '''

        # 接收参数
        params_str = request.body.decode()

        # 校验参数
        if not params_str:
            return JsonResponse({'code':'4001'})

        # 获取参数
        dict_params = json.loads(params_str)
        article_id = dict_params['article_id']
        pay_method = dict_params['pay_method']
        total_amount = dict_params['total_amount']

        user = request.user
        # ⽣成订单编号：年⽉⽇时分秒+⽤户编号
        order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') +('%03d' % user.id)

        # ⽣成⽀付订单
        try:
            order =OrderInfo.objects.create(order_id=order_id, user=user, pay_method=pay_method,
                                            total_amount = total_amount, article_id = article_id)
        except DataError:
            return JsonResponse({'code': 4002, 'errormsg': '⽣成订单失败'})

        # 调用支付接口，获取支付链接地址
        # ⽣成登录⽀付宝连接
        params = alipay.direct_pay(subject='芒果头条%s'%order_id, out_trade_no=order_id, total_amount=total_amount,
                                   return_url='http://127.0.0.1:8000/checkPay/')

        # 拼接请求返回路由
        alipay_url = alipay.gateway + '?' + params

        # 响应结果
        return JsonResponse({'code':200,'errormsg':'OK','alipay_url':alipay_url})

class CheckPayView(LoginRequiredJSONMixin,View):
    '''验签并且保存订单'''

    def get(self,request):
        # 获取所有的request请求参数
        params = request.GET.dict()
        # 获取签名
        sign = params.pop('sign')

        # 验签 判断是否成功支付
        if alipay.verify(params, sign):
            # 读取order_id
            order_id = params.get('out_trade_no', '')
            # 读取支付宝流水号
            trade_id = params.get('trade_no')
            # 保存Payment模型类数据
            Payment.objects.create(order_id=order_id,trade_id=trade_id)

            # 修改订单状态为已完成
            OrderInfo.objects.filter(order_id=order_id, status=1).update(status=2)

            # 响应结果
            return render(request,'payment/pay_success.html',{'trade_id':trade_id})

        return http.HttpResponseForbidden('⾮法请求')